/*
 * 选项框
 */

#include "gui.h"
#include <stdlib.h>
#include <string.h>

void ACALLBACK __check_render(struct Area *who,
			       void *userdata)
{
	struct Checker *ck = (struct Checker *) userdata;
	int x, y;
	x = who -> _x;
	y = who -> _y;
	
	video_set_color(0, 0, 0);
	video_rectangle(x + 4, y + 4, x + 20, y + 20);
	if (ck -> value) {
		video_poly_start();
		video_poly_point(x + 6, y + 10);
		video_poly_point(x + 11, y + 15);
		video_poly_point(x + 21, y);
	}
	if (ck -> _font && ck -> _caption) {
		Image a;
		a = ttf_make_img(ck -> _font, ck -> _caption, ck -> _font_color);
		video_drawimg(a, x + 30, y);
		video_destory_img(a);
	}
	
}

void ACALLBACK __check_mouse_up(struct Area *who,
				 int button, int x, int y, 
				 void *userdata)
{
	struct Checker *ck = (struct Checker*) userdata;
	ck -> value = !ck -> value;
	if (ck -> change)
		(*ck -> change)(ck, ck -> value, ck -> userdata);
}

struct Checker *check_new(struct Panel *father, const char *cap, int x, int y,
			  int width, int height)
{
	struct Checker *ret;
	ret = malloc(sizeof(struct Checker));
	memset(ret, 0, sizeof(struct Checker));
	
	struct Area *a;
	int xx, yy;
	if (father) {		//换成绝对坐标
		a = father -> _area;
		xx = father -> _area -> _x + x;
		yy = father -> _area -> _y + y;
	} else {
		a = NULL;
		xx = x;
		yy = y;
	}
	ret -> _area = area_new(a, xx, yy, width, height);
	ret -> _area -> enable = 1;
	ret -> _area -> visual = 1;
	ret -> _area -> userdata = ret;
	ret -> _area -> user_render = __check_render;
	ret -> _area -> mouse_up = __check_mouse_up;
	
	if (cap)
		check_set_caption(ret, cap);
	
	ret -> _font = gui_get_font_small();
	return ret;
}

void check_set_caption(struct Checker *ck, const char *cap)
{
	if (ck -> _caption) free(ck -> _caption);
	ck -> _caption = malloc(strlen(cap) + 2);
	strcpy(ck -> _caption, cap);
}

void check_set_font(struct Checker *ck, Font font)
{
	ck -> _font = font;
}


void check_delete(struct Checker *ck)
{
	ck -> _area -> enable = 0;
	ck -> _area -> visual = 0;
	if (ck -> _caption) free(ck -> _caption);
	free(ck);
}

void check_set_color(struct Checker *ck, Uint32 color)
{
	ck -> _font_color = color;
}

void check_set_value(struct Checker *ck, int val)
{
	ck -> value = !ck -> value;
	if (ck -> change)
		(*ck -> change)(ck, ck -> value, ck -> userdata);
}

int check_get_value(struct Checker *ck)
{
	return ck -> value;
}

void check_change(struct Checker *ck, void ACALLBACK (*f)(struct Checker *bt, int value, void *userdata))
{
	ck -> change = f;
}
